package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domian.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
    //分页查询
    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize) {
        Page page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        queryWrapper.orderByDesc(Category::getUpdateTime);
        Page page2 = categoryService.page(page1, queryWrapper);
        return R.success(page2);
    }
    //新增
    @PostMapping
    public R<String> insert(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }
    //删除逻辑
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.delete(id);
        return R.success("删除成功");
    }
    //修改
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改信息成功");
    }

    //下拉列表查询
    @GetMapping("list")
    public R<List<Category>> list(Integer type) {
        LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery().eq(type!=null,Category::getType, type).orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
